package com.zadtek.sharkRider.activity;

import java.util.ArrayList;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.zadtek.sharkRider.R;
import com.zadtek.sharkRider.activity.adapter.OrderWaitAdapter;
import com.zadtek.sharkRider.activity.adapter.OrderWaitHelpAdapter;
import com.zadtek.sharkRider.activity.common.Common;
import com.zadtek.sharkRider.activity.common.Const;
import com.zadtek.sharkRider.activity.data.OrderWaitData;
import com.zadtek.sharkRider.activity.data.WaitQuOrderData;
import com.zadtek.sharkRider.frame.JsonProcessHelper;
import com.zadtek.sharkRider.views.LazyScrollView;
import com.zadtek.sharkRider.views.LazyScrollView.OnScrollListener;
import com.zadtek.sharkRider.views.MyListView;

/**
 * 待取货Activity
 * 
 * @author Administrator
 * 
 */
public class OrderqhActivity extends BaseActivity {

	private MyListView waitList, help_waitgoodlist;
	private TextView ordernull;
	OrderWaitAdapter waitadapter;
	OrderWaitHelpAdapter helpadapter ;
	private WaitQuOrderData OrderWaitList = new WaitQuOrderData();
	// private ArrayList<OrderWaitData> OrderWaitList= new
	// ArrayList<OrderWaitData>();
	OrderAsyncTask mOrderAsyn;
	public static Handler mHandler;
	private String emp_id = "";
	private SharedPreferences sp;
	private LazyScrollView waterfall_scroll;
	private View mHeaderView;// 头部的控件
	private TextView pulldown_header_text; // 头部面板
	private ArrayList<OrderWaitData> mWaitOrderList;//普通订单列表
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.waitgoodslist);

		sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
		emp_id = sp.getString("uid", "");
	
		Const.ORDER_FLAGS = 1;// 判断新任务列表是否刷新 0-刷新；1-不刷新
		waitList = (MyListView) findViewById(R.id.waitgoodlist);
		help_waitgoodlist = (MyListView) findViewById(R.id.help_waitgoodlist);
		waterfall_scroll = (LazyScrollView) findViewById(R.id.waterfall_scroll);
		ordernull = (TextView) findViewById(R.id.ordernull);
		/**
		 * 头部和底部刷新
		 */
		mHeaderView = findViewById(R.id.mHeaderView);
		pulldown_header_text = (TextView) findViewById(R.id.pulldown_header_text);
		pulldown_header_text.setText("刷新中...");

		mHandler = new Handler() {
			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case Const.STATE_START_SUCCESS://
					closeProgressDialog();
					OrderWaitList = new WaitQuOrderData();
					OrderWaitList = (WaitQuOrderData) msg.obj;
					mHeaderView.setVisibility(View.GONE);

					if (OrderWaitList != null && !OrderWaitList.equals("")
							&& !OrderWaitList.equals("null")) {
						mWaitOrderList = OrderWaitList.getWaitdata();
						if ((!mWaitOrderList.get(0).getStatus01()
								.equals("0") && mWaitOrderList != null)
								|| (!OrderWaitList.getWaithelpData().get(0)
										.getStatus().equals("0") && OrderWaitList
										.getWaithelpData() != null)) {

							if (mWaitOrderList != null
									&& !mWaitOrderList.get(0)
											.getStatus01().equals("0")) {
								getGpsaddr(); // 反查地址
								waitList.setVisibility(View.VISIBLE);
								ordernull.setVisibility(View.GONE);
								waitadapter = new OrderWaitAdapter(
										OrderqhActivity.this,
										mWaitOrderList,
										R.layout.waitgoodslist_item);
								waitList.setAdapter(waitadapter);

							}else{
								waitList.setVisibility(View.GONE);
							}
							if (OrderWaitList.getWaithelpData() != null
									&& !OrderWaitList.getWaithelpData().get(0)
											.getStatus().equals("0")) {
								help_waitgoodlist.setVisibility(View.VISIBLE);
								ordernull.setVisibility(View.GONE);
								 helpadapter = new OrderWaitHelpAdapter(
										OrderqhActivity.this,
										OrderWaitList.getWaithelpData(),
										R.layout.helpwaitlist_item);
								help_waitgoodlist.setAdapter(helpadapter);
							}else{
								help_waitgoodlist.setVisibility(View.GONE);
							}

							InitLayout();
						} else {
							waitList.setVisibility(View.GONE);
							help_waitgoodlist.setVisibility(View.GONE);
							ordernull.setVisibility(View.VISIBLE);
						}
					} else {
						Common.DisplayToast(OrderqhActivity.this, "暂无数据！", 1);
					}
					break;
				case Const.STATE_START_ERROR://
					closeProgressDialog();
					Common.DisplayToast(OrderqhActivity.this, "获取数据失败", 1);
					break;
				}
			}
		};

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (Common.isNetworkConnected(OrderqhActivity.this)) {
			// showProgressDialog("数据加载中...");
			mHeaderView.setVisibility(View.VISIBLE);
			mOrderAsyn = new OrderAsyncTask();
			mOrderAsyn.execute("waitlist");
		} else {
			closeProgressDialog();
			Common.DisplayToast(OrderqhActivity.this, "通信失败,请检查网络!", 1);
		}
	}

	// 根据经纬度获取地址
	private void getGpsaddr() {
		int size = mWaitOrderList.size();
		for (int i = 0; i < size; i++) {
			try {
				OrderWaitData dataobj =mWaitOrderList.get(i);
				String phoneaddr = dataobj.getOrderItemList().get(0)
						.getPhone_addr();
				String address_road = dataobj.getAddress_road();
				if (address_road == null || address_road.equals("")
						|| address_road.equals("null")) {
					if (phoneaddr != null && !phoneaddr.equals("")
							&& !phoneaddr.equals("null")) {
						String[] latlng = phoneaddr.split(",");
						double lng = Double.parseDouble(latlng[0]);
						double lat = Double.parseDouble(latlng[1]);
						getgpssAddress(lat, lng, dataobj, i);
					}
				}
			} catch (Exception e) {
			}
		}
	}

	// 反查的
	void getgpssAddress(double lat, double lng, final OrderWaitData dataobj,
			final int positon) {
		GeocodeSearch geocoderSearch = new GeocodeSearch(this);
		geocoderSearch
				.setOnGeocodeSearchListener(new OnGeocodeSearchListener() {
					@Override
					public void onGeocodeSearched(GeocodeResult result,
							int rCode) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onRegeocodeSearched(RegeocodeResult result,
							int rCode) {
						if (rCode == 1000) {
							String formatAddress = result.getRegeocodeAddress()
									.getFormatAddress();
							try {
								dataobj.setGps_addrs(formatAddress);
								mWaitOrderList.set(positon, dataobj);
								OrderWaitList.setWaitdata(mWaitOrderList);
								if(waitadapter!=null) {
									waitadapter.notifyDataSetChanged();
								}
								
							} catch (Exception e) {
							}
						}
					}
				});
		LatLonPoint lp = new LatLonPoint(lat, lng);
		RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
		geocoderSearch.getFromLocationAsyn(query);
	}

	// 初始化面板
	private void InitLayout() {
		waterfall_scroll.getView();
		waterfall_scroll.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onTop() {
				// // 滚动到最顶端
				mHeaderView.setVisibility(View.VISIBLE);
				if (Common.isNetworkConnected(OrderqhActivity.this)) {
					mOrderAsyn = new OrderAsyncTask();
					mOrderAsyn.execute("waitlist");
				} else {
					closeProgressDialog();
					Common.DisplayToast(OrderqhActivity.this, "通信失败,请检查网络!", 1);
				}
			}

			@Override
			public void onScroll() {
				// 滚动中
			}

			@Override
			public void onBottom() {
			}
		});
	}

	class OrderAsyncTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String res = "";
			if (params[0].equals("waitlist")) {// 新任务列表数据
				OrderWaitList = new WaitQuOrderData();
				OrderWaitList = JsonProcessHelper.jsonProcess_getGetorderList(
						"get_rr_help_wait_order_list", emp_id);
				if (OrderWaitList != null) {
					res = "state_success";
				} else {
					res = "mi_error";
				}
			}
			return res;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result.equals("state_success")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_SUCCESS;
				msg.obj = OrderWaitList;
				mHandler.sendMessage(msg);
			} else if (result.equals("mi_error")) {
				Message msg = Message.obtain();
				msg.what = Const.STATE_START_ERROR;
				mHandler.sendMessage(msg);
			}
		}
	}

}
